<template>
  <div id="app" class="app-container">
    <el-config-provider :locale="locale">
      <router-view v-slot="{ Component, route }">
        <transition name="fade-transform" mode="out-in">
          <keep-alive :include="cachedViews">
            <component :is="Component" :key="route.path" />
          </keep-alive>
        </transition>
      </router-view>
    </el-config-provider>

    <!-- Global loading -->
    <el-loading
      v-loading="globalLoading"
      :text="loadingText"
      background="rgba(0, 0, 0, 0.8)"
      element-loading-spinner="el-icon-loading"
    />

    <!-- Network status indicator -->
    <transition name="slide-up">
      <div v-if="!isOnline" class="network-status offline">
        <el-icon><Connection /></el-icon>
        <span>网络连接已断开</span>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElConfigProvider, ElLoading, ElMessage } from 'element-plus'
import { Connection } from '@element-plus/icons-vue'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { useAppStore } from './stores/app'
import { useDeviceStore } from './stores/device'

// Stores
const appStore = useAppStore()
const deviceStore = useDeviceStore()
const router = useRouter()

// Reactive data
const locale = ref(zhCn)
const isOnline = ref(navigator.onLine)
const globalLoading = ref(false)
const loadingText = ref('加载中...')

// Computed
const cachedViews = computed(() => appStore.cachedViews)

// Network status handlers
const handleOnline = () => {
  isOnline.value = true
  ElMessage.success('网络连接已恢复')
  // Refresh data when network is back
  deviceStore.refreshDevices()
}

const handleOffline = () => {
  isOnline.value = false
  ElMessage.warning('网络连接已断开')
}

// Global loading control
const showGlobalLoading = (text = '加载中...') => {
  globalLoading.value = true
  loadingText.value = text
}

const hideGlobalLoading = () => {
  globalLoading.value = false
}

// Router guards
router.beforeEach((to, from, next) => {
  // Show loading for route changes
  if (to.meta.loading !== false) {
    showGlobalLoading('页面加载中...')
  }

  // Set page title
  if (to.meta.title) {
    document.title = `${to.meta.title} - ONVIF设备管理系统`
  } else {
    document.title = 'ONVIF设备管理系统'
  }

  next()
})

router.afterEach(() => {
  // Hide loading after route change
  setTimeout(() => {
    hideGlobalLoading()
  }, 300)
})

// Error handling
const handleGlobalError = error => {
  console.error('Global error:', error)
  hideGlobalLoading()
  ElMessage.error('系统发生错误，请稍后重试')
}

// Keyboard shortcuts
const handleKeydown = event => {
  // Ctrl/Cmd + R: Refresh current page
  if ((event.ctrlKey || event.metaKey) && event.key === 'r') {
    event.preventDefault()
    window.location.reload()
  }

  // Ctrl/Cmd + /: Show help
  if ((event.ctrlKey || event.metaKey) && event.key === '/') {
    event.preventDefault()
    ElMessage.info('快捷键：Ctrl+R 刷新页面')
  }
}

// Lifecycle
onMounted(() => {
  // Add event listeners
  window.addEventListener('online', handleOnline)
  window.addEventListener('offline', handleOffline)
  window.addEventListener('error', handleGlobalError)
  window.addEventListener('keydown', handleKeydown)

  // Initialize app
  appStore.initializeApp()

  // Check for updates periodically
  setInterval(() => {
    if (isOnline.value) {
      deviceStore.checkDeviceStatus()
    }
  }, 30000) // Check every 30 seconds

  console.log('🎉 App mounted successfully')
})

onUnmounted(() => {
  // Remove event listeners
  window.removeEventListener('online', handleOnline)
  window.removeEventListener('offline', handleOffline)
  window.removeEventListener('error', handleGlobalError)
  window.removeEventListener('keydown', handleKeydown)
})

// Expose methods to global
window.showGlobalLoading = showGlobalLoading
window.hideGlobalLoading = hideGlobalLoading
</script>

<style lang="scss">
.app-container {
  height: 100vh;
  overflow: hidden;
  background-color: var(--el-bg-color-page);
}

// Transition animations
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s ease;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s ease;
}

.slide-up-enter-from,
.slide-up-leave-to {
  transform: translateY(100%);
  opacity: 0;
}

// Network status indicator
.network-status {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 9999;
  padding: 12px 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

  &.offline {
    background-color: var(--el-color-danger);
    color: white;
  }

  .el-icon {
    font-size: 16px;
  }
}

// Global loading overlay
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.9) !important;

  .el-loading-spinner {
    .el-loading-text {
      color: var(--el-color-primary);
      font-weight: 500;
    }
  }
}

// Dark mode support
.dark {
  .el-loading-mask {
    background-color: rgba(0, 0, 0, 0.8) !important;

    .el-loading-spinner {
      .el-loading-text {
        color: var(--el-color-primary-light-3);
      }
    }
  }
}

// Responsive design
@media (max-width: 768px) {
  .network-status {
    bottom: 10px;
    left: 10px;
    right: 10px;
    transform: none;
    justify-content: center;
  }
}

// Print styles
@media print {
  .network-status,
  .el-loading-mask {
    display: none !important;
  }
}
</style>
